<?php
class CategoryController extends Vnf_Controller_Action {
    function init() {

        $this->view->maximizeWin = true; // maximize window after popup
        $this->view->winWidth = 640; // default width of window
        $this->view->winHeight = 480; // default height of window
        parent::init();

        $this->setLayout('admin');

        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');

        $this->view->currentController = $this->_request->getControllerName();
        $this->view->objName = "Category"; // class name of Model
        $objName = $this->view->objName;
        $this->view->objModel = $obj = new $objName();

        $this->view->pk = $obj->getPrimaryKey();
    }

    public function indexAction() {
//        Zend_Layout::getLayout('content');
    }

    public function dataAction() {
        $obj = $this->view->objModel;

        $records = $obj->getRecords();

        //        print_r($records);die;
        //        $records = $records->toArray();

        $result = array();
        $newName = "1";
        $$newName = 0;
        $flagRoot = true;
        $defaultParent = '';
        $parent = '';
        foreach ($records as $row) {
            // these line use to get path of category
            $newID = $row['category_id'];
            $parentID = $row['parent'];
            if ($row['parent'] == 0 || $row['parent'] == null)
            $$newID = $row['admin_title'];
            else $$newID = $$parentID . ' >> ' . $row['admin_title'];

            // replace current category from path

            $tmp['path'] = str_replace(">> {$row['admin_title']}", "", $$newID);
            //            $$newID = $row['admin_title'];
            $tmp['_id'] = $row['category_id'];
            $tmp['parent'] = $row['parent'];
            $tmp['admin_title'] = $row['admin_title'];
            $tmp['status'] = $row['status'];
            $tmp['_lft'] = $row['left'];
            $tmp['_rgt'] = $row['right'];
            $tmp['_level'] = $row['level'];
            $tmp['main_menu'] = $row['main_menu'];
            $tmp['template_id'] = $row['template_id'];
            $tmp['short_description'] = $row['short_description'];
            $tmp['description'] = $row['description'];
            $tmp['main_image'] = $row['main_image'];
            $tmp['action'] =  "<span style='cursor:pointer;color:green;' onclick='MyDesktop.CategoryManagement.editCategory();'>Edit</span>";
            $tmp['action'] .=  " - <span style='cursor:pointer;color:red;' onclick='MyDesktop.CategoryManagement.deleteCategory();'>Delete</span>";

            if($row['left'] == ($row['right'] - 1)) {
                $tmp['_is_leaf'] = 'true';
            } else {
                $tmp['_is_leaf'] = 'false';
            }
            $result[] = $tmp;
            $flagRoot = false;
        }

        $results = array(
            'success' => true,
            'total' => count($records),
            'data' => $result
        );



        echo Zend_Json::encode($results);die;
    }

    public function deleteAction() {
        $id = (int)$this->getRequest()->getParam('id', -1);
        $result = array();
        if($id > 0) {
            $obj = $this->view->objModel;
            $pk = $obj->getPrimaryKey();

            $obj->delete("'$id'");
            $result['success'] = true;
        }

        $strResult = Zend_Json::encode($result);
        echo $strResult;die;
    }

    public function saveAction() {
        $pk = $this->view->pk;

        $id = (int)$this->getRequest()->getParam("_id", -1);

        $params = $this->_request->getParams();
        $data = array(
            'admin_title' => @$params['admin_title'],
                    'template_id' => @$params['template_id'],
                    'main_menu' => @$params['main_menu'],
                    'main_image' => @$params['main_image'],

        //            'right' => @$params['right'],
            'status' => @$params['status']?$params['status']:1,
            'short_description' => @$params['short_description'],
            'description' => @$params['description'],
        );

        $obj = $this->view->objModel;

        $root = $obj->getRoot();
        //        print_r($root);die;

        $rootId = $root->category_id;


        $result = array();
        $result['success'] = false;
        if ($id > 0) { // update
            try {

                $uploadPath = UPLOAD_PATH . "/" . $this->_request->getControllerName();
                $fieldUpload = "main_image";
                $newImageName = '';
                if(@$params['main_image_delete'] != 1) {
                    try {
                        if(Zend_Upload::isFileUpload($fieldUpload)) {
                            if(!is_dir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath))
                            mkdir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath, 0777);
                            chmod($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath, 0777);
                            $newImageName = time(). '_' . rand();
                            $objImageUpload = new Zend_Upload($fieldUpload, $_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath);
                            echo "/*" . $objImageUpload->getName() . "*/";
                            $objImageUpload->setName($newImageName);
                            $objImageUpload->upload();
                            $newImageName = $uploadPath . "/" . $newImageName . "." .$objImageUpload->getFileExtention();
                        } else {
                            $where = "$pk = '$id'";
                            $oldRecord = $obj->fetchRow($where);
                            @$newImageName = $oldRecord->$fieldUpload;
                        }
                    } catch (Zend_Upload_Exception $ex){ }
                }
                $data[$fieldUpload] = $newImageName;


                // save to DB
                $where = "`category_id` = $id";
                $obj->update($data, $where);

                // update parent
                $currentCategory = $obj->getCategoryById($id);
                $currentParent = $currentCategory->parent;
                if (isset($params['parent']) && $params['parent'] != 0 && $params['parent'] != '' && $params['parent'] != $currentParent) {
                    echo "/*<pre>";
                    echo "curr - " . $currentParent;
                    echo "\r\n";
                    echo "new - " . $params['parent'];
                    echo "</pre>*/";
                    $obj->move($id, $params['parent']);
                }

                //                $newParent

                $result['success'] = true;
                $result['message'] = $this->view->translate->_("Save successfull.");
            } catch (Exception $ex){
                $result['success'] = false;
                $result['message'] = $this->view->translate->_("Can't save to DB.") . "<br>" . $ex->getMessage();
            }
        } else { // add
            try {
                $uploadPath = UPLOAD_PATH . "/" . $this->_request->getControllerName();
                $fieldUpload = 'main_image';
                $newImageName = '';
                try {
                    if(Zend_Upload::isFileUpload($fieldUpload)) {
                        if(!is_dir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath))
                        mkdir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath, 0777);
                        chmod($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath, 0777);

                        $newImageName = time(). '_' . rand();
                        $objImageUpload = new Zend_Upload($fieldUpload, $_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath);
                        $objImageUpload->setName($newImageName);
                        $objImageUpload->upload();
                        $saveImgName = $newImageName . "." .$objImageUpload->getFileExtention();
                        $newImageName = $uploadPath . "/" . $newImageName . "." .$objImageUpload->getFileExtention();
                    }
                    $data[$fieldUpload] = $newImageName;
                } catch (Zend_Upload_Exception $ex){
                    $result['success'] = true;
                    $result['message'] = $this->view->translate->_("Insert successfull.");
                }


                if (isset($params['parent']) && $params['parent'] != 0 && $params['parent'] != '')
                $data['parent'] = $params['parent'];
                else $data['parent'] =$rootId;
                $obj->insert($data);
                $result['success'] = true;
                $result['message'] = $this->view->translate->_("Insert successfull.");
            } catch(Exception $ex) {
                $result['message'] = $this->view->translate->_("Can't insert to DB") . "<br>" . $ex->getMessage();
            }
        }
        $strResult = Zend_Json::encode($result);
        //echo $strResult;die;
    }

    public function prepareAddAction() {
        // get parent of node
        $this->view->pid = $pid = $this->_getParam("pid", 0);

        $objCategory = new Category();
        $root = $objCategory->getRoot();
        if ($pid > 0) {
            // get path fron root to parent node
            $allParents = $objCategory->getPath($pid);
            $strParent = "";
            if (count($allParents) > 0) {
                foreach ($allParents as $row) {
                    if ($row->left != 1)
                       $strParent .= $strParent==""?$row->admin_title:" >> ".$row->admin_title;
                }
            }
            // assign string path of parent to view layer
            $this->view->strParent = $strParent;
        }
        $this->view->rootId = $root['category_id']; // default width of window
        $this->view->winWidth = 500; // default width of window
        $this->view->winHeight = 250; // default height of window
    }

    public function addProcessAction() {
        $parentId = $this->_getParam("parentid", 0);
        $nodeName = $this->_getParam("name", "");

        $obj = new Category();

        $data = array(
            'admin_title' => $nodeName,
            'parent' => $parentId,
            'status' => 1
        );

        $result = array();
        $result['success'] = false;
        try {
            $obj->insert($data);
            $result['success'] = true;
            $result['message'] = $this->view->translate->_("Insert successfull.");
        } catch(Exception $ex) {
            $result['message'] = $this->view->translate->_("Can't insert to DB") . "<br>" . $ex->getMessage();
        }

        $strResult = Zend_Json::encode($result);
        echo $strResult;die;

    }

    public function orderTreeAction() {
        $currentID = $this->_getParam("id", 0);
        $this->view->currentID = $currentID;


    }

    public function getTreeAction() {
        $drag_and_drop = $this->_request->getParam("dd", true);
        $root_id = (int)$this->_request->getParam("root", 0);
        $category = new Category();

        $tree = $category->getTreeOfNode($root_id, null, $drag_and_drop, null);

        echo Zend_Json::encode(array($tree));die;
    }

    public function reorderAction() {
        $obj = new Category();

        $cid = $this->_request->getParam('cid', 0); // move this node to reference node
        $rid = $this->_request->getParam('rid', 0); // reference node
        $pid = $this->_request->getParam('pid', -1); // parent node
        $ord = $this->_request->getParam('ord', "true"); // parent node
        if ($cid > 0) {
            if ($pid > 0 ) {
                // change parent of node
                try {
                    $obj->move($cid, $pid);
//                    echo "true";
                } catch (Exception $ex){
                    echo "false";die;
                }
            }
            try {
                if (($ord == "true") && ($rid > 0))
                    $obj->order($cid, $rid);
                echo "true";
            } catch (Exception $ex){
                echo "false";
            }
        }
        die;
    }
    function listAction() {
        
        $this->prepareData();
        
        $obj = new Category();

        $page = $this->_request->getParam('page'); // get the requested page
        $limit = $this->_request->getParam('rows', 20); // get how many rows we want to have into the grid
        $sidx = $this->_request->getParam('sidx', 'admin_title'); // get index row - i.e. user click to sort
        $sord = $this->_request->getParam('sord', 'ASC'); // get the direction if(!$sidx) $sidx =1;


        
        $this->view->subPage = $subPage = $this->getParam('id', null);
        
        $root = $obj->getRoot();
        $root_id = $root->category_id;
        
        if (null === $subPage){
            $where = "parent = $root_id";
        } else {
            $where = "parent = '$subPage'";
        }

        //echo $where;die;
        
        
        $this->view->countTotal = $count = $obj->getTotalRecords($where);
        //die;
        
        $page = $page>0 ? $page:1;
        if( $count > 0 ) {
            $total_pages = ceil($count/$limit);
        } else {
            $total_pages = 0;
        }
        if ($page > $total_pages)
            $page=$total_pages;
            
        $start = $limit*$page - $limit; // do not put $limit*($page - 1)
        $this->view->start = $start = $start>0 ? $start:0;
        
        //$records = $obj->getRecords($where, $sidx, $limit, $start);
        $records = $obj->getRecordsNormal($where, "$sidx $sord", $limit, $start);

        $responce = array();
        $responce['page'] = $page;
        $responce['total'] = $total_pages;
        $responce['records'] = $count;

        $i=0;
        $rows = array();
        /*
        foreach($records as $row):
            //print_r($row);die;
            $rows[$i]['id'] = $row['category_id'];
            $rows[$i]['cell'] = array(
                $row['category_id'],
                $row['admin_title'],
                $row['parent'],
                $row['description'],
                $row['keywords'],
                $row['tag_description'],
                $row['friendly_url'],
                $row['SortPriority'],
                $row['FeaturedCategory'],
            );
            $i++;
        endforeach;
        $responce['rows'] = $rows;
        */
        
        $this->view->results = $records;
        
        //print_r($records);
        
            $this->view->totalRecords = $totalRecords = $count;

            $currentPaging = $page;
            $currentPaging--;
            $numberPageView = 20;
            $recordsPerPage = $limit;
            $recordsPerPage = $recordsPerPage > 0? $recordsPerPage:20;
            $totalPages = ceil($totalRecords/$recordsPerPage);
            $this->view->pages = $totalPages;

            //echo $currentPage;
            $link =  BASE_URL . "/category/list/";
            $tagID = "showbycat";
            $startRecord = $recordsPerPage * $currentPaging;
            //$order = 'CommentID DESC';
            $class = "paging";

            $paging = new Paging();
            $this->view->paging = $paging->getPaging($currentPaging + 1, $totalPages, $link, $numberPageView, $tagID, $class,'false');
        //echo Zend_Json::encode($responce);die;
    }
    
    public function detailAction() {
    
        $this->prepareData();
        
        
        $id = (int)$this->getParam('id', 0);
        
        if ($id > 0) {
            /*$obj = new Category();
            
            $where = "category_id = '$id'";
            $this->view->records = $records = $obj->getRecordsNormal($where);
            */
            
            $allCategory = $this->view->allCategory;
            
            $this->view->records = $allCategory[$id];
        }
    }
    
    public function addAction() {
        $this->prepareData();
        $this->view->pa_id = $pa_id = (int)$this->getRequest()->getParam("pa_id", 0);
        if ($this->getParam('submit') == 'submit') {
            $pk = $this->view->pk;

            $id = (int)$this->getRequest()->getParam("_id", -1);

            $params = $this->_request->getParams();
            $data = array(
                'admin_title' => @$params['admin_title'],
                        //'template_id' => @$params['template_id'],
                        'FeaturedCategory' => @$params['FeaturedCategory']?$params['FeaturedCategory']:0,
                        'main_image' => @$params['main_image'],
                        'photo_link' => @$params['photo_link'],
                        'embed_youtube' => @$params['embed_youtube'],

            //            'right' => @$params['right'],
                'status' => @$params['status']?$params['status']:1,
                //'short_description' => @$params['short_description'],
                'description' => @$params['description'],
            );

            $obj = $this->view->objModel;

            $root = $obj->getRoot();
            //        print_r($root);die;

            $rootId = $root->category_id;


            $result = array();
            $result['success'] = false;
            if ($id > 0) { // update
                try {

                    // save to DB
                    $where = "`category_id` = $id";
                    $obj->update($data, $where);

                    // update parent
                    $currentCategory = $obj->getCategoryById($id);
                    $currentParent = $currentCategory->parent;
                    if (isset($params['parent']) && $params['parent'] != 0 && $params['parent'] != '' && $params['parent'] != $currentParent) {
                        echo "/*<pre>";
                        echo "curr - " . $currentParent;
                        echo "\r\n";
                        echo "new - " . $params['parent'];
                        echo "</pre>*/";
                        $obj->move($id, $params['parent']);
                    }

                    //                $newParent

                    $result['success'] = true;
                    $result['message'] = $this->view->translate->_("Save successfull.");
                } catch (Exception $ex){
                    $result['success'] = false;
                    $result['message'] = $this->view->translate->_("Can't save to DB.") . "<br>" . $ex->getMessage();
                }
            } else { // add
                try {

                    if (isset($params['parent']) && $params['parent'] != 0 && $params['parent'] != '')
                    $data['parent'] = $params['parent'];
                    else $data['parent'] =$rootId;
                    $obj->insert($data);
                    $result['success'] = true;
                    $result['message'] = $this->view->translate->_("Insert successfull.");
                } catch(Exception $ex) {
                    $result['message'] = $this->view->translate->_("Can't insert to DB") . "<br>" . $ex->getMessage();
                }
                
                if (isset($params['parent']) && $params['parent'] != 0 && $params['parent'] != '')
                    $this->_redirect("category/detail/?id=" . $params['parent']);
            }
            //$strResult = Zend_Json::encode($result);
            
            $this->view->message = $result['message'];
            //echo $strResult;die;
        }
    }
    
    public function updatefunctionAction() {
        $allId = $this->getParam('deleteid');
        
        $obj = new Category();
        if (count($allId) > 0) {
            foreach($allId as $id):
                $obj->delete("'$id'");
            endforeach;
        }
        
        $this->_redirect("category/list");
    }
    
    public function editAction() {
        $this->prepareData();
        
        $allCategory = $this->view->allCategory;
        
        $id = (int)$this->getRequest()->getParam("id", -1);
        if($id > 0) {
            $cat = @$allCategory[$id];
            $this->view->category = $cat;
        }
        
        if ($this->getParam('submit') == 'submit') {
            $pk = $this->view->pk;


            $params = $this->_request->getParams();
            $data = array(
                'admin_title' => @$params['admin_title'],
                        //'template_id' => @$params['template_id'],
                        'FeaturedCategory' => @$params['FeaturedCategory']?$params['FeaturedCategory']:0,
                        'main_image' => @$params['main_image'],
                        'photo_link' => @$params['photo_link'],
                        'embed_youtube' => @$params['embed_youtube'],

            //            'right' => @$params['right'],
                'status' => @$params['status']?$params['status']:1,
                //'short_description' => @$params['short_description'],
                'description' => @$params['description'],
            );

            $obj = $this->view->objModel;

            $root = $obj->getRoot();
            //        print_r($root);die;

            $rootId = $root->category_id;


            $result = array();
            $result['success'] = false;
            if ($id > 0) { // update
                try {

                    // save to DB
                    $where = "`category_id` = $id";
                    $obj->update($data, $where);

                    // update parent
                    $currentCategory = $obj->getCategoryById($id);
                    $currentParent = $currentCategory->parent;
                    if (isset($params['parent']) && $params['parent'] != 0 && $params['parent'] != '' && $params['parent'] != $currentParent) {
                        echo "/*<pre>";
                        echo "curr - " . $currentParent;
                        echo "\r\n";
                        echo "new - " . $params['parent'];
                        echo "</pre>*/";
                        $obj->move($id, $params['parent']);
                    }

                    //                $newParent

                    $result['success'] = true;
                    $result['message'] = $this->view->translate->_("Save successfull.");
                } catch (Exception $ex){
                    $result['success'] = false;
                    $result['message'] = $this->view->translate->_("Can't save to DB.") . "<br>" . $ex->getMessage();
                }
            }
            //$strResult = Zend_Json::encode($result);
            
            $this->view->message = $result['message'];
            //echo $strResult;die;
            $obj = $this->view->objModel;
            $pk = $obj->getPrimaryKey();
            //$this->view->category = $obj->fetchRow("$pk = '$id'");
            $allCategory = $obj->getCacheOfCategory();
            
            $id = (int)$this->getRequest()->getParam("id", -1);
            if($id > 0) {
                $cat = @$allCategory[$id];
                $this->view->category = $cat;
                $this->_redirect("category/detail/?id=" . $id);
            }
        } else {
            
            //$obj = $this->view->objModel;
            //$pk = $obj->getPrimaryKey();
            
        }
    }
    
}